package com.hsg.common.thirdloginutil.login.twitter

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.OAuthCredential
import com.google.firebase.auth.OAuthProvider
import com.hsg.common.thirdloginutil.bean.ThirdLoginRespond
import com.hsg.common.thirdloginutil.login.LoginInterface

/**
 * Twitter 登入
 */
class TwitterLogin(
    private val activity: Activity,
    private val loginCallback: (respond: ThirdLoginRespond?) -> Unit
) : LoginInterface {

    private val GOOGLE_AUTH_PROVIDER_NAME = "twitter.com"
    private var firebaseAuth: FirebaseAuth? = null

    override fun startLogin() {
        twitterLogin()
    }

    override fun handleLoginResult(requestCode: Int, resultCode: Int, data: Intent?) {

    }

    private fun twitterLogin() {
        val provider: OAuthProvider.Builder = OAuthProvider.newBuilder(GOOGLE_AUTH_PROVIDER_NAME)
        firebaseAuth = FirebaseAuth.getInstance()
        val pendingResultTask: Task<AuthResult>? = firebaseAuth?.pendingAuthResult
        if (pendingResultTask != null) {
            // There's something already here! Finish the sign-in for your user.
            pendingResultTask
                .addOnSuccessListener(
                    OnSuccessListener {
                        // User is signed in.
                        // IdP data available in
                        // authResult.getAdditionalUserInfo().getProfile().
                        // The OAuth access token can also be retrieved:
                        // authResult.getCredential().getAccessToken().
                        // The OAuth secret can be retrieved by calling:
                        // authResult.getCredential().getSecret().
                        handleTwitterLogin(it)
                    })
                .addOnFailureListener {
                    it.printStackTrace()
                    loginCallback(null)
                }
        } else {
            // There's no pending result so you need to start the sign-in flow.
            // See below.
            firebaseAuth!!
                .startActivityForSignInWithProvider(activity, provider.build())
                .addOnSuccessListener {
                    // User is signed in.
                    // IdP data available in
                    // authResult.getAdditionalUserInfo().getProfile().
                    // The OAuth access token can also be retrieved:
                    // authResult.getCredential().getAccessToken().
                    // The OAuth secret can be retrieved by calling:
                    // authResult.getCredential().getSecret().
                    handleTwitterLogin(it)
                }
                .addOnFailureListener {
                    // Handle failure.
                    it.printStackTrace()
                    loginCallback(null)
                }

        }
    }

    private fun handleTwitterLogin(authResult: AuthResult) {
        val userName = authResult.additionalUserInfo?.username
        val accessToken = (authResult.credential as OAuthCredential).accessToken
        val secret = (authResult.credential as OAuthCredential).secret
        val thirdId = authResult.additionalUserInfo?.profile?.get("id_str") as String
        if (TextUtils.isEmpty(accessToken)) {
            loginCallback(null)
        } else {
            val respond = ThirdLoginRespond(
                thirdId,
                accessToken,
                userName,
                null,
                null,
                secret
            )
            loginCallback(respond)
        }
    }

    override fun signOut() {
        firebaseAuth?.signOut()
    }

}